<template>
  <el-container style="flex-direction: column; height: 100vh;">
    <!-- 顶部栏 -->
    <HeaderComponent :userInfo="this.userInfo" />

    <!-- 主内容区 -->
    <el-container style="flex-direction: row; height: 100vh;">
      <!-- 侧边栏 -->
      <SidebarComponent />
      <el-main style="overflow-y: auto;">
        <div class="property-user-view">
          <h2>用户管理</h2>

          <div class="operation-bar">
            <el-card style="width: 100%; border-color: aqua;">
              <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="用户名" style="margin-left: 20px;">
                  <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="地址" style="margin-left: 20px;">
                  <el-input v-model="queryParams.address" placeholder="请输入地址" clearable />
                </el-form-item>
                <el-form-item label="角色" style="margin-left: 20px;">
                  <el-select v-model="queryParams.status" placeholder="请选择角色" clearable>
                    <el-option label="管理员" value=1 />
                    <el-option label="普通用户" value=2 />
                  </el-select>
                </el-form-item>
                <el-form-item style="margin-left: 20px;">
                  <el-button type="primary" @click="getUsers">查询</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <div class="user-list">
            <h3>用户列表</h3>
            <el-table :data="this.users" style="width: 100%" header-cell-class-name="header-center">
              <el-table-column prop="name" label="用户名" align="center">
                <template #default="scope">
                  <span>{{ scope.row.username }}</span>
                  <span v-if="isCurrentUser(scope.row)" style="color: #67C23A; margin-left: 5px;">(当前用户)</span>
                </template>
              </el-table-column>
              <el-table-column prop="image" label="头像" align="center">
                <template #default="scope">
                  <el-image style="width: 80px; height: 80px; border-radius: 4px;" :src="scope.row.image"
                    :preview-src-list="[scope.row.image]" fit="cover" />
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号" align="center" />
              <el-table-column prop="status" label="角色" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'primary' : 'success'">
                    {{ scope.row.status === 1 ? '管理员' : '普通用户' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit"
                    @click="showUserDetail(scope.row)">详情</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete"
                    @click="deleteUser(scope.row.id)">注销</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 20px; text-align: center;" background
              layout="total, sizes, prev, pager, next, jumper" :total="this.total" :page-sizes="[5, 10, 20]"
              :page-size="pageSize" :current-page="page" @size-change="handleSizeChange"
              @current-change="handlePageChange" />
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 用户详情弹窗 -->
    <el-dialog title="用户详情" :visible.sync="detailDialogVisible" width="30%">
      <el-form :model="currentUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" disabled />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="currentUser.phone" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.email" disabled />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="currentUser.address" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-tag :type="currentUser.status === 1 ? 'primary' : 'success'"
            @click="handleChangeStatus(currentUser.status)">
            {{ currentUser.status === 1 ? '管理员' : '普通用户' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="头像">
          <el-image style="width: 80px; height: 80px; border-radius: 4px;" :src="currentUser.image"
            :preview-src-list="[currentUser.image]" fit="cover" />
        </el-form-item>
        <el-form-item label="业主姓名">
          <el-input v-model="currentUser.ownerName" disabled />
        </el-form-item>
        <el-form-item label="产权编号">
          <el-input v-model="currentUser.propertyNumber" disabled />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
    HeaderComponent,
    SidebarComponent
  },
  data() {
    return {
      userInfo: {},
      users: [],
      total: 0,
      queryParams: {
        username: '',
        address: '',
        status: ''
      },
      page: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      detailDialogVisible: false, // 控制详情弹窗显示
      currentUser: { // 当前查看详情的用户
        id: '', // 用户id
        username: '', // 用户名
        phone: '', // 手机号
        email: '', // 邮箱
        address: '', // 地址
        status: '', // 角色
        image: '', // 头像
        ownerName: '', // 业主姓名
        propertyNumber: '', // 产权编号
      }
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getUsers();
  },
  methods: {
    // 获取用户列表
    getUsers() {
      service.get('/api/admin/user/GetAllUsers', {
        params: {
          username: this.queryParams.username,
          address: this.queryParams.address,
          status: this.queryParams.status,
          page: this.page,
          pageSize: this.pageSize,
        }
      }).then(result => {
        result = result.data;
        this.users = result.data.rows || [];
        this.total = result.data.total;
        console.log(this.users);
      })
        .catch((error) => {
          console.error(error);
        });
    },

    // 判断是否为当前用户
    isCurrentUser(user) {
      return user.id === this.userInfo.id; // 假设 userInfo 中有 id 字段
    },

    /**
     * 改变账号权限
     * @param status 
     */
    handleChangeStatus(status) {
      if (status === 1) {
        this.$confirm('确定将用户角色改为普通用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          service.get('/api/admin/user/changeUserStatus', {
            params: {
              id: this.currentUser.id,
              status: 2,
            }
          }).then(result => {
            result = result.data;
            if (result.code === 1) {
              this.$message.success('修改成功');
              this.getUsers();
            } else {
              this.$message.error(result.msg);
            }
          }).catch(error => {
            this.$message.error('修改失败');
            console.error(error);
          })
        }).catch(() => {
          // 当用户点击取消按钮时执行的代码
          this.$message.info('已取消删除操作');
        });
      }
      else if (status === 2) {
        this.$confirm('确定将用户角色改为管理员吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          service.get('/api/admin/user/changeUserStatus', {
            params: {
              id: this.currentUser.id,
              status: 1,
            }
          }).then(result => {
            result = result.data;
            if (result.code === 1) {
              this.$message.success('修改成功');
              this.getUsers();
            } else {
              this.$message.error(result.msg);
            }
          }).catch(error => {
            this.$message.error('修改失败');
            console.error(error);
          })
        }).catch(() => {
          // 当用户点击取消按钮时执行的代码
          this.$message.info('已取消删除操作');
        });
      }
    },

    // 删除用户
    deleteUser(userId) {
      this.$confirm('确定删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.get(`/api/admin/user/deleteUser/${userId}`).then(result => {
          result = result.data;
          if (result.code === 1) {
            this.$message.success('删除成功');
            this.getUsers();
          } else {
            this.$message.error(result.msg);
          }
        }).catch(error => {
          this.$message.error('删除失败');
          console.error(error);
        });
      }).catch(() => {
        // 当用户点击取消按钮时执行的代码
        this.$message.info('已取消删除操作');
      });
    },

    // 查看用户详情
    showUserDetail(user) {
      this.currentUser = { ...user };
      this.detailDialogVisible = true;
    },

    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        username: '',
        address: '',
        status: ''
      };
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.page = 1; // 重置为第一页
      this.getUsers();
    },

    // 页码变化
    handlePageChange(page) {
      this.page = page;
      this.getUsers();
    }
  }
};
</script>

<style scoped>
.property-user-view {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.user-list {
  margin-top: 20px;
}
</style>